package com.xianggu.designMode.decorator.demo02;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @author chengjy
 * @date 2025/3/19
 */
public class BufferReadFile extends FileInputStream {

    private final byte[] buffer;

    private int index = -1;
    private int size = -1;

    public BufferReadFile(int size, File file) throws FileNotFoundException {
        super(file);
        this.buffer = new byte[size];
    }

    @Override
    public int read() throws IOException {
        // 判断是否可以读取
        if(isReadable()){
            return bufferReadData();
        }
        refreshBuffer();
        if(!isReadable()){
            return -1;
        }
        return bufferReadData();
    }

    private int bufferReadData() {
        if(index >= size){
            return -1;
        }
        return buffer[index++] & 0xff;
    }

    private void refreshBuffer() {
        try {
            // 重置游标
            index = 0;
            // 有效数据指标
            size = super.read(buffer);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private boolean isReadable() {
        // 指标越界
        if(index >= size){
            return false;
        }
        // 缓存中无数据
        return true;
    }
}
